package com.atguigu.guli.service.edu.service.impl;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.edu.entity.CourseCollect;
import com.atguigu.guli.service.edu.entity.vo.CourseCollectVo;
import com.atguigu.guli.service.edu.mapper.CourseCollectMapper;
import com.atguigu.guli.service.edu.mapper.CourseMapper;
import com.atguigu.guli.service.edu.service.CourseCollectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程收藏 服务实现类
 * </p>
 *
 * @author Helen
 * @since 2020-04-01
 */
@Service
public class CourseCollectServiceImpl extends ServiceImpl<CourseCollectMapper, CourseCollect> implements CourseCollectService {


    @Autowired
    private CourseMapper courseMapper;

    @Override
    public void saveCourseById(String courseId, String memberId) {

        // 判断是否已经收藏
        if(isCollect(courseId,memberId)){
            return;
        }

        CourseCollect courseCollect = new CourseCollect();
        courseCollect
                .setCourseId(courseId)
                .setMemberId(memberId);

        int insert = baseMapper.insert(courseCollect);
        if(insert < 1){
            throw new GuliException("课程收藏失败",1231);
        }
    }

    /**
     * 判断用户是否已经收藏
     * @param courseId
     * @param memberId
     * @return
     */
    @Override
    public boolean isCollect(String courseId, String memberId) {
        QueryWrapper<CourseCollect> courseCollectQueryWrapper = new QueryWrapper<>();
        courseCollectQueryWrapper
                .eq("member_id",memberId)
                .eq("course_id",courseId);

        Integer integer = baseMapper.selectCount(courseCollectQueryWrapper);

        return integer.intValue() > 0;
    }


    /**
     * 用户收藏列表
     * @param memberId
     * @return
     */
    @Override
    public List<CourseCollectVo> selectListByMemberId(String memberId) {
        return baseMapper.selectPageByMemberId(memberId);
    }

    @Override
    public Boolean removeCourseCollectById(String courseId, String memberId) {
        if(isCollect(courseId,memberId)){
            QueryWrapper<CourseCollect> courseCollectQueryWrapper = new QueryWrapper<>();
            courseCollectQueryWrapper
                    .eq("member_id",memberId)
                    .eq("course_id",courseId);
            return remove(courseCollectQueryWrapper);
        }
        return false;
    }
}
